import api from '../../common/config/api-url'
import Vue from 'vue'

export default {
  login: data => {
    return new Promise(resolve => {
      Vue.prototype.$u.post(api.user.login + '?code=' + data.code).then(
        r => {
          if (r) {
            if (r.code === 0) {
              uni.setStorageSync('openid', r.data.openid)
              uni.setStorageSync('token', r.data.token || '')
              uni.setStorageSync('userId', r.data.userId || '')
              if (r.data.token) {
                wx.switchTab({
                  url: `/pages/my/index`
                })
              }
              resolve({msg: '获取成功'})
            }
          }
        },
        e => {
          wx.showToast({
            title: e.msg,
            icon: 'none',
            duration: 2000
          })
        }
      )
    })
  },
  sendCode: data => {
    return new Promise(resolve => {
      Vue.prototype.$u.post(api.user.sendCode + '?mobile=' + data).then(
        r => {
          if (r) {
            if (r.code === 0) {
              resolve(r.code)
            } else {
              if (r.code === 500) {
                wx.showToast({
                  title: r.msg,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          }
        },
        e => {
          wx.showToast({
            title: e.msg,
            icon: 'none',
            duration: 2000
          })
        }
      )
    })
  },
  register: data => {
    return new Promise(resolve => {
      Vue.prototype.$u.post(api.user.register, data).then(
        r => {
          if (r) {
            if (r.code === 0) {
              uni.setStorageSync('token', r.data.token)
              uni.setStorageSync('userId', r.data.userId)
              resolve(r)
            }
          }
        },
        e => {
          wx.showToast({
            title: e.msg,
            icon: 'none',
            duration: 2000
          })
        }
      )
    })
  }
}
